﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using CNFM_CROCODILE_LOGO.Core.Domain.ViewModels;
using CNFM_CROCODILE_LOGO.RestClient.Utils;
using CNFM_CROCODILE_LOGO.Services.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CNFM_CROCODILE_LOGO_Web.Controllers
{
    /// <summary>
    /// 标识申请单
    /// </summary>
    public class SignageApplicationController : Controller
    {
        private ISignageServices _pro;
        private readonly IHostingEnvironment _ihe;
        public SignageApplicationController(ISignageServices pro, IHostingEnvironment ihe)
        {
            this._pro = pro;
            this._ihe = ihe;
        }

        /// <summary>
        /// 申请单列表
        /// </summary>
        /// <returns></returns>
        public IActionResult List()
        {
            return View();
        }

        /// <summary>
        /// 申请单初审列表
        /// </summary>
        /// <returns></returns>
        public IActionResult ListOne()
        {
            return View();
        }

        /// <summary>
        /// 申请单复审列表
        /// </summary>
        /// <returns></returns>
        public IActionResult ListTwo()
        {
            return View();
        }

        /// <summary>
        /// 申请单修改
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string id)
        {
            var result = _pro.GetSignageApplication(id);
            var json = JsonConvert.SerializeObject(result.Result);
            JObject obj = JObject.Parse(json);
            SignageApplicationReceiptModels entity = JsonConvert.DeserializeObject<SignageApplicationReceiptModels>(obj["Data"].ToString());
            return View(entity);
        }

        /// <summary>
        /// 申请单
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            return View();
        }

        /// <summary>
        /// 申请单初审
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult OneReview(string id)
        {

            var result = _pro.GetSignageApplication(id);
            var json = JsonConvert.SerializeObject(result.Result);
            JObject obj = JObject.Parse(json);
            SignageApplicationReceiptModels entity = JsonConvert.DeserializeObject<SignageApplicationReceiptModels>(obj["Data"].ToString());

            SignageApplicationReview entitys = new SignageApplicationReview()
            {
                Id = entity.Id,
                ApplyNum = entity.ApplyNum
            };
            return View(entitys);
        }

        /// <summary>
        /// 申请单复审
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult TwoReview(string id)
        {
            var result = _pro.GetSignageApplication(id);
            var json = JsonConvert.SerializeObject(result.Result);
            JObject obj = JObject.Parse(json);
            SignageApplicationReceiptModels entity = JsonConvert.DeserializeObject<SignageApplicationReceiptModels>(obj["Data"].ToString());

            SignageApplicationReview entitys = new SignageApplicationReview()
            {
                Id = entity.Id,
                ApplyNum = entity.ApplyNum,
                OneToExamineNum = entity.OneToExamineNum
            };
            return View(entitys);
        }

        /// <summary>
        /// 标识分配列表
        /// </summary>
        /// <returns></returns>
        public IActionResult AllotmentList()
        {
            return View();
        }

        /// <summary>
        /// 标识导入
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult AllotmentEdit(string id, string enId, string spId, string name, string quantity)
        {
            ViewBag.Id = id;
            ViewBag.EnId = enId;
            ViewBag.SpId = spId;
            ViewBag.Name = name;
            ViewBag.Quantity = quantity;
            return View();
        }

        /// <summary>
        /// 单次配发
        /// </summary>
        /// <param name="id"></param>
        /// <param name="enId"></param>
        /// <param name="spId"></param>
        /// <returns></returns>
        public IActionResult SingleEdit(string id, string enId, string spId, string name, string quantity)
        {
            ViewBag.Id = id;
            ViewBag.EnId = enId;
            ViewBag.SpId = spId;
            ViewBag.Name = name;
            ViewBag.Quantity = quantity;
            return View();
        }

        /// <summary>
        /// 标识查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult AllotmentQuire()
        {
            return View();
        }

        /// <summary>
        /// 批量激活
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult QuireEdit(string id, string name, string saNo)
        {
            ViewBag.Id = id;
            ViewBag.Name = name;
            ViewBag.SaNo = saNo;
            return View();
        }

        /// <summary>
        /// 多选激活
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="saNo"></param>
        /// <returns></returns>
        public IActionResult QuireAllEdit()
        {
            return View();
        }


        /// <summary>
        /// 激活列表
        /// </summary>
        /// <returns></returns>
        public IActionResult ActivationList()
        {
            return View();
        }

        /// <summary>
        /// 申请单列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="areUnCode"></param>
        /// <param name="status"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        [Authorize("Permission")]
        public JsonResult GetSignageApplicationAll(int index, int size, string areUnCode, string enterpriseId, string status, string sasearch, string epId)
        {
            //epId 
            if (epId != "undefined" && epId != "null" && !string.IsNullOrEmpty(epId))
                enterpriseId = epId;
            var ret = _pro.GetSignageApplicationAll(index, size, areUnCode, enterpriseId, status, sasearch);
            return Json(ret);
        }

        /// <summary>
        /// 申请单列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="areUnCode"></param>
        /// <param name="enterpriseId"></param>
        /// <param name="status"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        [Authorize("Permission")]
        public JsonResult GetSignageApplicationTwoAll(int index, int size, string areUnCode, string enterpriseId, string status, string sasearch)
        {
            var ret = _pro.GetSignageApplicationAll(index, size, areUnCode, enterpriseId, status, sasearch);
            return Json(ret);
        }

        /// <summary>
        /// 申请单新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddUpdateSignageApplication([FromBody]SignageApplicationReceiptModels model)
        {
            var ret = _pro.AddUpdateSignageApplication(model);
            return Json(ret);
        }

        /// <summary>
        /// 申请单停用
        /// </summary>
        /// <param name="signagId"></param>
        /// <returns></returns>
        [HttpDelete]
        public JsonResult DeleteSignageApplication(string signagId)
        {
            var ret = _pro.DeleteSignageApplication(signagId);
            return Json(ret);
        }

        /// <summary>
        /// 产品列表
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public JsonResult GetSpeciesManageTypeAll(string type)
        {
            var ret = _pro.GetSpeciesManageTypeAll(type);
            return Json(ret);
        }

        /// <summary>
        /// 标识申请单初审
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ReviewSignageApplicationOne([FromBody]SignageApplicationReview model)
        {
            var ret = _pro.ReviewSignageApplicationOne(model);
            return Json(ret);
        }

        /// <summary>
        /// 标识申请单复审
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ReviewSignageApplicationTwo([FromBody]SignageApplicationReview model)
        {
            var ret = _pro.ReviewSignageApplicationTwo(model);
            return Json(ret);
        }

        /// <summary>
        /// 标识列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="enterpriseId"></param>
        /// <param name="speciesManageId"></param>
        /// <param name="status"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        [Authorize("Permission")]
        public JsonResult GetIdentificationAll(int index, int size, string enterpriseId, string areUnCode, string speciesManageId, string status, string sasearch)
        {
            var ret = _pro.GetIdentificationAll(index, size, enterpriseId, areUnCode, speciesManageId, status, sasearch);
            return Json(ret);
        }

        /// <summary>
        /// 标识激活
        /// </summary>
        /// <param name="identifId"></param>
        /// <returns></returns>
        public JsonResult UpdateIdentification(string identifId)
        {
            var ret = _pro.UpdateIdentification(identifId);
            return Json(ret);
        }


        /// <summary>
        /// 标签导入
        /// </summary>
        /// <param name="bllId"></param>
        /// <param name="bllType"></param>
        /// <param name="type"></param>
        /// <param name="typeInt"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddIdentification(string enterpriseId, string speciesManageId, string signageApplicationReceiptId, string registeredTime)
        {
            var Files = Request.Form.Files["file"];

            string tempName = string.Empty;
            string excelName = string.Empty;

            IdentificationModels identificationAll = new IdentificationModels()
            {
                EnterpriseId = enterpriseId,
                SignageApplicationReceiptId = signageApplicationReceiptId,
                SpeciesManageId = speciesManageId,
                RegisteredTime = Convert.ToDateTime(registeredTime)
            };
            var IdentificationsAll = new List<IdentificationsModels>();

            var files = Request.Form.Files;

            var fileName = ContentDispositionHeaderValue.Parse(Files.ContentDisposition).FileName.Trim('"');

            string filePath = _ihe.WebRootPath + $@"\Files\Excel\";

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            int index = fileName.LastIndexOf('.');
            //从下一个索引开始截取
            string suffix = fileName.Substring(index + 1);
            // string suffix = fileName.Split('.')[2];

            if (!suffix.Contains("xls") && !suffix.Contains("xlsx"))
            {
                return Ok(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("格式错误!"));
            }

            fileName = Guid.NewGuid() + "." + suffix;

            string fileFullName = filePath + fileName;

            using (FileStream fs = System.IO.File.Create(fileFullName))
            {
                Files.CopyTo(fs);
                fs.Flush();
                excelName = fs.Name;
            }
            //filePathResultList.Add($"/Files/Pictures/{fileName}");



            var ImportTables = excelName.ReadExcel(0, excelName);

            //if (ImportTables == null)
            //    return;
            //datatable数据插入
            foreach (DataRow dr in ImportTables.Rows)
            {
                IdentificationsModels identifications = new IdentificationsModels();
                //获取此模型的公共属性
                PropertyInfo[] propertys = identifications.GetType().GetProperties();
                //遍历该对象所有属性
                foreach (PropertyInfo pi in propertys)
                {
                    //将属性名称复制给临时变量
                    tempName = pi.Name;
                    //检查DataTable是否包含此列
                    if (ImportTables.Columns.Contains(tempName))
                    {
                        //取值
                        object value = dr[tempName];
                        //非空，赋值
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(identifications, value, null);
                        }
                    }
                }
                //对象插入
                IdentificationsAll.Add(identifications);
            }

            identificationAll.IdentificationList = IdentificationsAll;

            if (Directory.Exists(filePath))
            {

                Directory.Delete(filePath, true);

            }

            var ret = _pro.AddIdentification(identificationAll);
            return Json(ret);
            //定义变量

        }

        /// <summary>
        /// 通过HttpClient获取另外站点的文件流，再输出        
        /// </summary>
        /// <returns></returns>
        public IActionResult DownLoad()
        {
            try
            {

                var filePath = "/Files/Excel/12345678.xls";
                var fileName = "标签导入模板.xls";
                FileStream fs = new FileStream(_ihe.WebRootPath + filePath, FileMode.OpenOrCreate);
                fs.Close();
                return File(new FileStream(_ihe.WebRootPath + filePath, FileMode.Open), "application/octet-stream", fileName);
            }
            catch (Exception ex)
            {
                return NotFound();
            }
        }

        /// <summary>
        /// 指定激活(单个)
        /// </summary>
        /// <param name="qrCode"></param>
        /// <returns></returns>
        public JsonResult UpdateSpecifyActivation(string qrCode)
        {
            var ret = _pro.UpdateSpecifyActivation(qrCode);
            return Json(ret);
        }

        /// <summary>
        /// 指定激活(批量)
        /// </summary>
        /// <param name="qrCodes"></param>
        /// <returns></returns>
        public JsonResult UpdateSpecifyActivationAll(string qrCodes)
        {
            var ret = _pro.UpdateSpecifyActivationAll(qrCodes);
            return Json(ret);
        }

        /// <summary>
        /// 标识多选激活   
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize("Permission")]
        public JsonResult UpdateActivationAll([FromBody]List<LogoStockModels> models)
        {
            var ret = _pro.UpdateActivationAll(models);
            return Json(ret);
        }
    }
}